package com.scau.ums.controller;

import com.scau.ums.mapper.DormareaMapper;
import com.scau.ums.mapper.MaintaingroupMapper;
import com.scau.ums.mapper.MaintainroleMapper;
import com.scau.ums.model.*;
import com.scau.ums.service.AddUserService;
import com.scau.ums.service.imp.password.CommonPasswordImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import  com.scau.ums.util.excel.ExcelUtil;
import sun.applet.Main;

/**
 * 描述：处理用户信息录入的控制类
 * @author xfy
 * @version 1.0
 * @date 2019/7/22 9:56
 */
@Controller
public class AddUserController {
    //复用伟杰的错误转发页面
    private String errorPage = "/WEB-INF/jsp/authorityError.jsp";

    /**
     * 用户信息录入service
     */
    @Autowired
    AddUserService service;
    @Autowired
    MaintaingroupMapper maintaingroupMapper;
    @Autowired
    MaintainroleMapper maintainroleMapper;
    @Autowired
    DormareaMapper dormareaMapper;
    @Autowired
    CommonPasswordImp commonPasswordImp;
    @Autowired
    DataSourceTransactionManager transactionManager;

    @RequestMapping("/addUser")
    public String userManagementGet(HttpServletRequest request){
        HttpSession session = request.getSession();

        if(session.getAttribute("dormArea") == null){
            List<Dormarea> dormareaList = dormareaMapper.selectByExample(null);
            session.setAttribute("dormArea", dormareaList);
            System.out.println("宿舍：" + dormareaList.get(0).getArea());
        }
        if(session.getAttribute("maintainGroup") == null){
            List<Maintaingroup> groupList = maintaingroupMapper.selectByExample(null);
            session.setAttribute("maintainGroup", groupList);
        }
        if(session.getAttribute("maintainRole") == null){
            List<Maintainrole> roleList = maintainroleMapper.selectByExample(null);
            session.setAttribute("maintainRole", roleList);
        }
        return "addUser";
    }

    /**
     * 处理手动录入学生信息的Get请求和Post请求
     * @return
     */
    @RequestMapping(value = "/uploadStudentByHand", method = RequestMethod.GET)
    public String studentUploadByHandGet(){
        return "uploadStudentByHand";
    }

    @RequestMapping(value = "/uploadStudentByHand", method = RequestMethod.POST)
    public String studentUploadByHandPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Student student = new Student();

        try {
            student.setId(request.getParameter("stuId"));
            student.setPassword(commonPasswordImp.encode(request.getParameter("stuId")));
            student.setName(request.getParameter("stuName"));
            student.setMajor(request.getParameter("major"));
            student.setClasses(Integer.valueOf(request.getParameter("classes")));
            student.setSex(request.getParameter("stuSex"));
            student.setTelephone(request.getParameter("stuTelephone"));
            student.setMail(request.getParameter("stuEmail"));
            student.setDormregion(request.getParameter("stuDormRegion"));
            student.setDormbuilding(Integer.valueOf(request.getParameter("stuDormBuilding")));
            student.setDormroom(Integer.valueOf(request.getParameter("stuDormRoom")));
            System.out.println(student);
            service.addStudent(student);
        } catch (Exception e) {
            e.printStackTrace();

            request.setAttribute("msg", "录入用户失败，请确认是否有信息填写错误！");
            request.setAttribute("redirect","/addUser");
            request.getRequestDispatcher(errorPage).forward(request,response);
            return "uploadStudentByHand";
        }
        request.setAttribute("msg", "录入用户成功~");
        request.setAttribute("redirect","/addUser");
        request.getRequestDispatcher(errorPage).forward(request,response);
        return "uploadStudentByHand";
    }

    /**
     * 处理手动录入教师信息的Get请求和Post请求
     * @return
     */
    @RequestMapping(value = "/uploadTeacherByHand", method = RequestMethod.GET)
    public String teacherUploadByHandGet(){
        return "uploadTeacherByHand";
    }

    @RequestMapping(value = "/uploadTeacherByHand", method = RequestMethod.POST)
    public String teacherUploadByHandPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Teacher teacher = new Teacher();

        try{
            teacher.setId(request.getParameter("teaId"));
            teacher.setPassword(commonPasswordImp.encode(request.getParameter("teaId")));
            teacher.setName(request.getParameter("teaName"));
            teacher.setSex(request.getParameter("teaSex"));
            teacher.setTelephone(request.getParameter("teaTelephone"));
            teacher.setMail(request.getParameter("teaEmail"));
            teacher.setDormregion(request.getParameter("teaDormRegion"));
            teacher.setDormbuilding(Integer.valueOf(request.getParameter("teaDormBuilding")));
            teacher.setDormroom(Integer.valueOf(request.getParameter("teaDormRoom")));
            System.out.println(teacher);

            service.addTeacher(teacher);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "录入用户失败，请确认是否有信息填写错误！");
            request.setAttribute("redirect","/addUser");
            request.getRequestDispatcher(errorPage).forward(request,response);
            return "uploadTeacherByHand";
        }
        request.setAttribute("msg", "录入用户成功！");
        request.setAttribute("redirect","/addUser");
        request.getRequestDispatcher(errorPage).forward(request,response);
        return "uploadTeacherByHand";
    }

    /**
     * 处理手动录入维修部信息的Get请求和Post请求
     * @return
     */
    @RequestMapping(value = "/uploadMaintainerByHand", produces="text/json;charset=utf-8", method = RequestMethod.GET)
    @ResponseBody
    public String maintainerUploadByHandGet(){
        return "uploadMaintainerByHand";
    }

    @RequestMapping(value = "/uploadMaintainerByHand", method = RequestMethod.POST)
    public String maintainerUploadByHandPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Maintainer maintainer = new Maintainer();

        try{
            maintainer.setId(request.getParameter("maintainerId"));
            maintainer.setPassword(commonPasswordImp.encode(request.getParameter("maintainerId")));
            maintainer.setName(request.getParameter("maintainerName"));
            maintainer.setSex(request.getParameter("maintainerSex"));
            maintainer.setTelephone(request.getParameter("maintainerTelephone"));
            maintainer.setMail(request.getParameter("maintainerEmail"));
            if(!request.getParameter("maintainGroup").equals(""))
                maintainer.setMaintainergroup(Integer.valueOf(request.getParameter("maintainGroup")));
            maintainer.setRole(Integer.valueOf(request.getParameter("maintainRole")));

            service.addMaintainer(maintainer);


        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "录入用户失败，请确认是否有信息填写错误！");
            request.setAttribute("redirect","/addUser");
            request.getRequestDispatcher(errorPage).forward(request,response);
            return "uploadMaintainerByHand";
        }
        request.setAttribute("msg", "录入用户成功~");
        request.setAttribute("redirect","/addUser");
        request.getRequestDispatcher(errorPage).forward(request,response);
        return "uploadMaintainerByHand";
    }


    /**
     * 处理上传录入学生信息的get请求
     * @return
     */
    @RequestMapping(value = "/uploadStudentByExcel", method = RequestMethod.GET)
    public String studentUploadByExcelGet() {
        return "uploadStudentByExcel";
    }
    /**
     * 处理上传录入学生信息的post请求
     * @return
     */
    @RequestMapping(value = "/uploadStudentByExcel", method = RequestMethod.POST)
    public String studentUploadByExcelPost(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //同时录入多个用户，需要事务管理，出错回滚
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        //统计成功插入数量
        int sum = 0;
        //获取请求的文件，前提是excel文件类型（xls、xlsx）
        MultipartFile file = ExcelUtil.getExcelByHttpRequest(request);
        Student stuTemp = new Student();
        if (file != null) {
            //获取文件的内容
            List<List<Object>> excelContent = ExcelUtil.getBankListByExcel(file.getInputStream(), file.getOriginalFilename());

            for (List<Object> record : excelContent) {
                try {
                    //id为空，跳过该条数据
                    if(record.get(0) == null || record.get(0).equals("")){
                        continue;
                    }
                    Student student = new Student();
                    student.setId(String.valueOf(record.get(0)));
                    student.setPassword(commonPasswordImp.encode(String.valueOf(record.get(0))));
                    student.setName(String.valueOf(record.get(1)));
                    student.setMajor(String.valueOf(record.get(2)));
                    student.setClasses(Integer.valueOf(String.valueOf(record.get(3))));
                    student.setSex(String.valueOf(record.get(4)));
                    student.setTelephone(String.valueOf(record.get(5)));
                    student.setMail(String.valueOf(record.get(6)));//设置邮箱
                    student.setDormregion(String.valueOf(record.get(7)));
                    student.setDormbuilding(Integer.valueOf(String.valueOf(record.get(8))));
                    student.setDormroom(Integer.valueOf(String.valueOf(record.get(9))));
                    stuTemp.setId(student.getId());
                    System.out.println("打印信息-->" + student.toString());
                    //调用service向数据库插入数据
                    sum += service.addStudent(student);
                } catch (Exception e) {
                    //数据库回滚
                    transactionManager.rollback(status);
                    request.setAttribute("msg", "学号为“" + stuTemp.getId() + "”的学生信息录入失败，请确认是否有信息填写错误并重新录入！");
                    request.setAttribute("redirect","/addUser");
                    request.getRequestDispatcher(errorPage).forward(request,response);
                    return "uploadStudentByExcel";
                }
            }
        }
        transactionManager.commit(status);
        String result = "成功录入" + sum + "条学生数据";
        request.setAttribute("msg", result);
        request.setAttribute("redirect","/addUser");
        request.getRequestDispatcher(errorPage).forward(request,response);
        return "uploadStudentByExcel";
    }

    /**
     * 处理上传录入教师信息的get求
     * @return
     */
    @RequestMapping(value = "/uploadTeacherByExcel", method = RequestMethod.GET)
    public String teacherUploadByExcelGet() {
        return "uploadTeacherByExcel";
    }

    /**
     * 处理上传录入教师信息的post请求
     * @return
     */
    @RequestMapping(value = "/uploadTeacherByExcel", method = RequestMethod.POST)
    public String teacherUploadByExcelPost(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //同时录入多个用户，需要事务管理，出错回滚
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());

        //统计成功插入数量
        int sum = 0;

        MultipartFile file = ExcelUtil.getExcelByHttpRequest(request);
        Teacher teaTemp = new Teacher();
        if (file != null) {
            List<List<Object>> excelContent = ExcelUtil.getBankListByExcel(file.getInputStream(), file.getOriginalFilename());

            for (List<Object> record : excelContent) {
                try {
                    //id为空，跳过该条数据
                    if(record.get(0) == null || record.get(0).equals("")){
                        continue;
                    }
                    Teacher teacher = new Teacher();
                    teacher.setId(String.valueOf(record.get(0)));
                    teacher.setPassword(commonPasswordImp.encode(String.valueOf(record.get(0))));
                    teacher.setName(String.valueOf(record.get(1)));
                    teacher.setSex(String.valueOf(record.get(2)));
                    teacher.setTelephone(String.valueOf(record.get(3)));
                    teacher.setMail(String.valueOf(record.get(4)));//设置邮箱
                    teacher.setDormregion(String.valueOf(record.get(5)));
                    teacher.setDormbuilding(Integer.valueOf(String.valueOf(record.get(6))));
                    teacher.setDormroom(Integer.valueOf(String.valueOf(record.get(7))));
                    teaTemp.setId(teacher.getId());
                    System.out.println("打印信息-->" + teacher.toString());
                    //调用service向数据库插入数据
                    sum += service.addTeacher(teacher);
                } catch (Exception e) {
                    //数据库回滚
                    transactionManager.rollback(status);

                    request.setAttribute("msg", "工号为“" + teaTemp.getId() + "”的教师信息录入失败，请确认是否有信息填写错误并重新录入！");
                    request.setAttribute("redirect","/addUser");
                    request.getRequestDispatcher(errorPage).forward(request,response);
                    return "uploadTeacherByExcel";
                }
            }
        }
        transactionManager.commit(status);

        String result = "成功录入" + sum + "条教师数据";
        System.out.println(result);
        request.setAttribute("msg", result);
        request.setAttribute("redirect","/addUser");
        request.getRequestDispatcher(errorPage).forward(request,response);
        return "uploadTeacherByExcel";
    }

    /**
     * 处理上传录入维修部门信息的get请求
     * @return
     */
    @RequestMapping(value = "/uploadMaintainerByExcel", method = RequestMethod.GET)
    public String maintainerUploadByExcelGet() {
        return "uploadMaintainerByExcel";
    }

    /**
     * 处理上传录入维修部门信息的post请求
     * @return
     */
    @RequestMapping(value = "/uploadMaintainerByExcel", method = RequestMethod.POST)
    public String maintainerUploadByExcelPost(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //同时录入多个用户，需要事务管理，出错回滚
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        //统计成功插入数量
        int sum = 0;

        MultipartFile file = ExcelUtil.getExcelByHttpRequest(request);
        Maintainer mainTemp = new Maintainer();
        if (file != null) {
            List<List<Object>> excelContent = ExcelUtil.getBankListByExcel(file.getInputStream(), file.getOriginalFilename());

            for (List<Object> record : excelContent) {

                try {
                    //id为空，跳过该条数据
                    if(record.get(0) == null || record.get(0).equals("")){
                        continue;
                    }
                    Maintainer maintainer = new Maintainer();
                    maintainer.setId(String.valueOf(record.get(0)));
                    maintainer.setPassword(commonPasswordImp.encode(String.valueOf(record.get(0))));
                    maintainer.setName(String.valueOf(record.get(1)));
                    maintainer.setSex(String.valueOf(record.get(2)));
                    maintainer.setTelephone(String.valueOf(record.get(3)));
                    maintainer.setMail(String.valueOf(record.get(4)));//设置邮箱
                    maintainer.setMaintainergroup(User.getMaintainerGroupByZhName(String.valueOf(record.get(5))));
                    System.out.println("组别：" + String.valueOf(record.get(5)) + "代码：" + User.getMaintainerGroupByZhName(String.valueOf(record.get(5))));
                    maintainer.setRole(User.getMaintainerRoleByZhName(String.valueOf(record.get(6))));
                    System.out.println("职位：" + String.valueOf(record.get(6)) + " 代码：" + User.getMaintainerRoleByZhName(String.valueOf(record.get(6))));
                    mainTemp.setId(maintainer.getId());
                    System.out.println("打印信息-->" + maintainer.toString());
                    //调用service向数据库插入数据
                    sum += service.addMaintainer(maintainer);
                } catch (Exception e) {
                    //数据库回滚
                    transactionManager.rollback(status);

                    request.setAttribute("msg", "工号为“" + mainTemp.getId() + "”的维修工信息录入失败，请确认是否有信息填写错误并重新录入！");
                    request.setAttribute("redirect","/addUser");
                    request.getRequestDispatcher(errorPage).forward(request,response);
                    return "uploadMaintainerByExcel";
                }
            }
        }
        transactionManager.commit(status);
        String result = "成功录入" + sum + "条维修部门数据";
        System.out.println(result);
        request.setAttribute("msg", result);
        request.setAttribute("redirect","/addUser");
        request.getRequestDispatcher(errorPage).forward(request,response);
        return "uploadMaintainerByExcel";
    }
}
